package org.syncsoft.overalt.gui.impl.componentPlugin;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComboBox;

import org.syncsoft.overalt.gui.api.WindowContextValue;
import org.syncsoft.overalt.gui.api.componentPlugin.IComponentPlugin;

/**
 * 
 * @author tptfc
 *
 */
public class ComboBoxComponentPlugin implements IComponentPlugin {
	private Map<String, JComboBox> combos;
	
	{
		setCombos(new HashMap<String, JComboBox>());
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.gui.swing.api.IComponentPlugin#getContext()
	 */
	@Override
	public WindowContextValue getContext() {
		WindowContextValue context = new WindowContextValue();
		buildContext(context);
		return context;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.gui.swing.api.IComponentPlugin#buildContext(org.syncsoft.overalt.gui.swing.api.ContextWindowValue)
	 */
	@Override
	public void buildContext(WindowContextValue context) {
		if (context != null) {
			for (String key : getCombos().keySet()) {
				context.addValue(key, getComboBoxComponentValue(key));
			}
		}
	}

	/**
	 * @precondition key and items not is null
	 * @param key
	 * @param items
	 * @return
	 */
	public JComboBox newComboBox(String key, Collection<?> items) {
		JComboBox combo = null;
		
		if (key != null && items != null && !items.isEmpty()) {
			combo = new JComboBox(items.toArray());
			getCombos().put(key, combo);
		}
		
		return combo;
	}
	
	/**
	 * 
	 * @param key
	 * @return
	 */
	public JComboBox getComboBox(String key) {
		return getCombos().get(key);
	}
	
	/**
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getComboBoxComponentValue(String key) {
		Object value = null;
		JComboBox combo = getComboBox(key);
		
		if (combo != null) {
			value = combo.getSelectedItem();
		}
		
		return (T) value;
	}
	
	private Map<String, JComboBox> getCombos() {
		return combos;
	}
	private void setCombos(Map<String, JComboBox> combos) {
		this.combos = combos;
	}

}
